﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Commons.Interfaces.GateWay;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Entities.Models;
using Atmk.WaterMeter.MIS.GateWay.CT_NBIoT.ViewModel.CallBack;
using Atmk.WaterMeter.MIS.Logic.TempLogic;
using Atmk.WaterMeter.MIS.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NLog;

namespace Atmk.WaterMeter.MIS.Controllers
{
    /// <summary>
    ///     信息接收--中国电信NB专用接口
    /// </summary>
    [Route("api/[controller]")]
    public class CT_CallbackController : Controller
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly ICT_NBIoTCallBackLogic _ctNbioTCallBackLogic;

        /// <inheritdoc />
        public CT_CallbackController(ICT_NBIoTCallBackLogic ctNbioTCallBackLogic)
        {
            _ctNbioTCallBackLogic = ctNbioTCallBackLogic;
        }

        /// <summary>
        ///     数据消息回调
        ///     https://firstdomainbyxiang.info:15000/api/AtmkCb/CommandCallback
        /// </summary>
        /// <param name="value"></param>
        //[HttpPost("deviceDatachanged")]
        //public async Task<IActionResult> DeviceDataChanged([FromBody] DeviceDataPost value)
        //{
        //    try
        //    {
        //        if (value != null)
        //        {
        //            //时间转换
        //            var eventTime = Simple.CtStringConvertDateTime2(value.service.eventTime);
        //            //_logger.Debug($"保存上传记录{value.ToString()}");
        //            using (var context = ContextBuilder.Build())
        //            {
        //                var meterCodeIdMap = await context.MeterCodeIdMap.FirstOrDefaultAsync(m => m.CtNbId == value.deviceId);
        //                if (meterCodeIdMap == null)
        //                    throw new Exception("没有找到对应水表编号");
        //                //异步向结算表插数据
        //                var NBCallback =new NBCallbackDAL();
        //                NBCallback.InsertSettlementDay(value.service.data, meterCodeIdMap, eventTime);
        //                //04磁报警攻击
        //                if (value.service.data.msgtype==4) 
        //                {
        //                    NBCallback.InsertWarningMagnetism(value.service.data, meterCodeIdMap, eventTime);
        //                }
        //                NBCallback.MeterRecordSave(value.service.data, meterCodeIdMap, eventTime);
        //                return Ok(new { errcode = 0, msg = "device data saved." });
        //                //new NBIoTCallBack().InsertSettlementDay(value.service.data, meterCodeIdMap, eventTime);
        //                //InsertSettlementDay(value.service.data, meterCodeIdMap, eventTime);
        //                //_ctNbioTCallBackLogic.MeterDatasLogic(value, meterCodeIdMap.Number, eventTime);
        //            }
        //        }
        //        else
        //        {
        //            _logger.Debug("电信回调数据消息：传入数据为空");
        //            return Ok(new { errcode = 1, msg = "CallBack Error" });
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        _logger.Error("数据消息回调：" + e.Message);
        //        return Ok(new { errcode = 1, msg = "CallBack Error" });
        //    }
        //}

        /// <summary>
        ///     https://firstdomainbyxiang.info:15000/api/AtmkCb/CommandCallback
        ///     指令状态
        /// </summary>
        /// <param name="value"></param>
        [HttpPost("CommandCallback")]
        public IActionResult CommandCallback([FromBody] CommandRespond value)
        {
            try
            {
                _logger.Debug("接收平台指令状态反馈");
                if (value != null)
                {
                    var result = JsonConvert.SerializeObject(value);
                    _logger.Debug($"接收数据{result}");
                    _ctNbioTCallBackLogic.CommandStatusLogic(value);
                }
                else
                {
                    _logger.Debug("CommandCallback传入数据为空值");
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
            }

            return Ok();
        }

        //public async void InsertSettlementDay(Entities.DeviceData serviceData, MeterCodeIdMap meterCodeIdMap, DateTime eventTime)
        //{
        //    await Task.Run(() =>
        //     {
        //         try
        //         {
        //             using (var context = new WaterMeterDBContext())
        //             {
        //                 var settlementDay_Today = context.SettlementDay.FirstOrDefault(m => m.MeterNumber == meterCodeIdMap.Number && m.ReadTime.ToString("yyyy-MM-dd") == eventTime.ToString("yyyy-MM-dd"));

        //                 var settlementDay_Yesterday = context.SettlementDay.Where(m => m.MeterNumber == meterCodeIdMap.Number).OrderByDescending(m => m.ReadTime).FirstOrDefault();
        //                 if (settlementDay_Yesterday != null && settlementDay_Yesterday.ReadTime.ToString("yyyy-MM-dd") == eventTime.ToString("yyyy-MM-dd"))
        //                 {
        //                     settlementDay_Yesterday = context.SettlementDay.Where(m => m.MeterNumber == meterCodeIdMap.Number && Convert.ToDateTime(m.ReadTime.ToString("yyyy-MM-dd")) < Convert.ToDateTime(eventTime.ToString("yyyy-MM-dd"))).OrderByDescending(m => m.ReadTime).FirstOrDefault();
        //                 }

        //                 var readString = Base64Convert.ConvertBytes(serviceData.current);
        //                 var readInt = BytesConvert.BitConvertInts(readString, 6).First() / 100.00;

        //                 if (settlementDay_Today == null)
        //                 {
        //                     var SettlementDayEntity = new SettlementDay()
        //                     {
        //                         MeterNumber = meterCodeIdMap.Number,
        //                         ReadTime = eventTime,
        //                         Value = readInt,
        //                         SettlementState = 0,
        //                         Dosage = settlementDay_Yesterday == null ? 0 : readInt - settlementDay_Yesterday.Value,
        //                         AreaId = meterCodeIdMap.AreaId,
        //                         DistrictId = meterCodeIdMap.DistrictId,
        //                         OwerId = meterCodeIdMap.OwerId,
        //                         MeterId = meterCodeIdMap.MeterId
        //                     };
        //                     context.SettlementDay.Add(SettlementDayEntity);
        //                     context.SaveChangesAsync();
        //                 }
        //                 else
        //                 {
        //                     settlementDay_Today.Value = readInt;
        //                     settlementDay_Today.Dosage = settlementDay_Yesterday == null ? 0 : readInt - settlementDay_Yesterday.Value;
        //                     settlementDay_Today.ReadTime = eventTime;
        //                     context.Update(settlementDay_Today);
        //                     context.SaveChangesAsync();
        //                 }

        //             }
        //         }
        //         catch (Exception ex)
        //         {
        //             _logger.Error($"InsertSettlementDay方法 记录数据异常：{ex.Message}");
        //         }
        //     });
        //}
    }
}